import React, { useEffect, useRef, useState } from 'react';
import { connect, useDispatch } from 'umi';
import { Drawer, Form, Button, Input, message, Select } from 'antd';
import RoleAuthUsers from '../RoleAuthUsers';

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const validateMessages = {
  required: "'${label}' 是必填项！",
};

const RoleAddEdit = (props) => {
  const { drawerType, handleClose, editData, appCodeOfSelect } = props;
  const [form] = Form.useForm();
  const selectUsertRef = useRef();
  const dispatch = useDispatch();
  const [detail, setDetail] = useState({ userList: [] });

  useEffect(() => {
    if (!editData.id) return;
    dispatch({
      type: 'commonRoleManageModel/getRoleDtail',
      payload: { roleId: editData.id },
    }).then((res) => {
      setDetail(res?.data);
      form.setFieldsValue(res?.data);
    });
  }, [editData]);

  const handleSubmit = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const params = {
        userIdList: selectUsertRef.current.getListOfSelectUserIds(),
        appCode: appCodeOfSelect,
        ...values,
      };
      let dispatchType = 'commonRoleManageModel/addRole';
      if (drawerType !== 'add') {
        params.id = editData.id;
        dispatchType = 'commonRoleManageModel/updateRole';
      }
      dispatch({
        type: dispatchType,
        payload: params,
      }).then((res) => {
        const { code, message: errMsg } = res;
        if (code === 0) {
          message.success(`${drawerType === 'add' ? '新增' : '编辑'}成功`);
          handleClose(true);
        } else {
          message.error(errMsg);
        }
      });
    });
  };

  return (
    <Drawer
      title={`${drawerType === 'add' ? '添加' : '修改'}角色`}
      width={600}
      visible
      onClose={() => handleClose()}
      bodyStyle={{ paddingBottom: 80 }}
      footer={
        <div style={{ textAlign: 'right' }}>
          <Button onClick={() => handleClose()} style={{ marginRight: 8 }}>
            {' '}
            取消
          </Button>
          <Button type="primary" onClick={handleSubmit}>
            {drawerType === 'add' ? '添加' : '保存'}
          </Button>
        </div>
      }
    >
      <Form {...layout} form={form} name="nest-messages" validateMessages={validateMessages}>
        <div style={{ marginBottom: 12, fontWeight: 'bold' }}>基本信息</div>
        <Form.Item name="roleCode" label="角色编号" rules={[{ required: true }]}>
          <Input placeholder="输入角色编号" />
        </Form.Item>
        <Form.Item name="roleName" label="角色名称" rules={[{ required: true }]}>
          <Input placeholder="输入角色名称" />
        </Form.Item>
        <Form.Item name="roleType" label="角色类型" rules={[{ required: true }]} initialValue={0}>
          <Select placeholder="选择角色类型" disabled>
            <Select.Option value={0}>公共角色</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item name="roleDesc" label="描述">
          <Input.TextArea rows={5} maxLength={255} placeholder="输入描述，限255字" />
        </Form.Item>
      </Form>
      <RoleAuthUsers
        ref={selectUsertRef}
        title="授权用户"
        userList={detail.userList}
        style={{ marginTop: 38 }}
        tbodyStyle={{ height: 410 }}
      />
    </Drawer>
  );
};

export default connect((state) => state)(RoleAddEdit);
